import { isObject } from "./utils"
import { mutableHandlers } from "./baseHandlers";

export const enum ReactiveFlags { 
  IS_REACTIVE = '__v_isReactive',
  IS_READONLY = '__v_isReadonly',
  RAW = '__v_raw',
  SKIP = '__v_skip'
}

export interface Target { 
  [ReactiveFlags.SKIP]?: boolean;
  [ReactiveFlags.IS_REACTIVE]?: boolean;
  [ReactiveFlags.IS_READONLY]?: boolean;
  [ReactiveFlags.RAW]?: any;
}

export const targetMap = new WeakMap<Target, any>()

export function reactive<T extends object>(target: T): T;
export function reactive(target: object) {
  // 如果target不是对象，直接返回
  if (!isObject(target)) { 
    return target;
  }

  // 如果是已经代理过的对象，就不需要再进行代理了
  if (targetMap.has(target)) {
    return targetMap.get(target);
  }

  // 判断是否是响应式对象
  if (target[ReactiveFlags.IS_REACTIVE]) { 
    return target;
  }

  const proxy = new Proxy(target, mutableHandlers);

  targetMap.set(target, proxy);

  return proxy;
}
